﻿using System;
using System.Diagnostics;
using System.Windows;
using Microsoft.Phone.Controls;

namespace Wp7Tools.Commands {
	public class GestureListenerEx : GestureListener {
		public string OnTapAction { get; set; }
		public string OnDoubleTapAction { get; set; }
		public string OnDragCompletedAction { get; set; }
		public string OnDragDeltaAction { get; set; }
		public string OnDragStartedAction { get; set; }
		public string OnFlickAction { get; set; }
		public string OnGestureBeginAction { get; set; }
		public string OnGestureCompletedAction { get; set; }
		public string OnHoldAction { get; set; }
		public string OnPinchCompletedAction { get; set; }
		public string OnPinchDeltaAction { get; set; }
		public string OnPinchStartedAction { get; set; }

		public GestureListenerEx() {
			Tap += (s, e) => CallAction(OnTapAction, s, e);
			DoubleTap += (s, e) => CallAction(OnDoubleTapAction, s, e);
			DragCompleted += (s, e) => CallAction(OnDragCompletedAction, s, e);
			DragDelta += (s, e) => CallAction(OnDragDeltaAction, s, e);
			DragStarted += (s, e) => CallAction(OnDragStartedAction, s, e);
			Flick += (s, e) => CallAction(OnFlickAction, s, e);
			GestureBegin += (s, e) => CallAction(OnGestureBeginAction, s, e);
			GestureCompleted += (s, e) => CallAction(OnGestureCompletedAction, s, e);
			Hold += (s, e) => CallAction(OnHoldAction, s, e);
			PinchCompleted += (s, e) => CallAction(OnPinchCompletedAction, s, e);
			PinchDelta += (s, e) => CallAction(OnPinchDeltaAction, s, e);
			PinchStarted += (s, e) => CallAction(OnPinchStartedAction, s, e);
		}

		private static void CallAction(string action, object sender, EventArgs e) {
			FrameworkElement frameworkElement = sender as FrameworkElement;
			if (frameworkElement == null) {
				return;
			}
			if (action == null) {
				return;
			}
			try {
				Reflector.CallMethod(frameworkElement.DataContext, action, e);
			}
			catch {
				Debug.WriteLine("Could not find method {0} in object {1}", action, frameworkElement.DataContext);
			}
		}
	}
}